<template>
  <div class="content">
    <div>
      <el-tabs v-model="activeIndex" closable v-if="openTab.length" @tab-click='tabClick' @tab-remove='tabRemove'>
        <el-tab-pane :key="item.name" v-for="(item, index) in openTab" :label="item.name" :name="item.route">
        </el-tab-pane>
      </el-tabs>
    </div>
    <router-view></router-view>
  </div>
</template>
<script>
import { dateFormat } from '@/utils/filter';
import { hex_md5 } from '@/utils/md5';

export default {
  data() {
    let validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入旧密码'));
      } else {
        callback();
      }
    };
    let validateNewPwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        callback();
      }
    };
    let validateConfirmPwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'));
      } else {
        callback();
      }
    };
    return {
      rootPath: '首页',
      systemTime: '',
      tabIndex: 0,
      dialogVisible: false,
      currentPath: '',
      form: {
        password: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        password: [{ required: true, validator: validatePassword, trigger: 'blur' }],
        newPassword: [{ required: true, validator: validateNewPwd, trigger: 'blur' }],
        confirmPassword: [
          { required: true, validator: validateConfirmPwd, trigger: 'blur' }
        ]
      },
      username: localStorage.username || '',
      activeName: 'first',

    };
  },

  watch: {

    '$route'(to, from) {
      //判断路由是否已经打开
      //已经打开的 ，将其置为active
      //未打开的，将其放入队列里
      let flag = false;
      for (let item of this.openTab) {

        if (item.name === to.name) {
          console.log('to.path', to.path);
          this.$store.commit('set_active_index', to.path)
          flag = true;
          break;
        }
      }

      if (!flag) {
        console.log('to.path', to.path);
        console.log('luyou ')
        this.$store.commit('add_tabs', { route: to.path, name: to.name });
        this.$store.commit('set_active_index', to.path);
      }

    }
  },
  mounted() {


    let timer;
    clearInterval(timer);
    // this.$router.push('/main/index')
    timer = setInterval(() => {
      this.systemTime = dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss');
    }, 1000);

    // 刷新时以当前路由做为tab加入tabs
    // 当前路由不是首页时，添加首页以及另一页到store里，并设置激活状态
    // 当当前路由是首页时，添加首页到store，并设置激活状态
    // alert(this.$route.path)
    if (this.$route.path !== '/' && this.$route.path !== '/main/index') {
      console.log('1');
      console.log(this.openTab)
      let flag = false;
      for (let item of this.openTab) {

        if (item.name === this.$route.name) {
          console.log('to.path', this.$route.path);
          this.$store.commit('set_active_index', this.$route.path)
          flag = true;
          break;
        }
      }

      if (!flag) {
        console.log('to.path', this.$route.path);
        console.log('luyou ')
        this.$store.commit('add_tabs', { route: this.$route.path, name: this.$route.name });
        this.$store.commit('set_active_index', this.$route.path);
      }
      // this.$store.commit('add_tabs', {route: '/main/index', name: '/main/index'});
      // this.$store.commit('add_tabs', { route: this.$route.path, name: this.$route.name });
      // this.$store.commit('set_active_index', this.$route.path);



    } else {
      console.log('2');
      this.$store.commit('add_tabs', { route: '/main/index', name: '首页' });
      this.$store.commit('set_active_index', '/main/index');
      this.$router.push('/main/index');
    }
  },
  computed: {
    openTab() {
      return this.$store.state.openTab;
    },
    activeIndex: {
      get() {
        return this.$store.state.activeIndex;
      },
      set(val) {
        this.$store.commit('set_active_index', val);
      }
    }
  },
  methods: {

    close() {
      this.$refs['form'].resetFields();
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    save() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.newPassword != this.form.confirmPassword) {
            this.$refs['confirmPassword'].validateState = 'error';
            this.$refs['confirmPassword'].validateMessage = '新密码与确认密码不一致';
            return;
          } else {
            let str = hex_md5('energy123');
            this.$common
              .$ajax(
                'manage/updatePassword', {
                  oldPassword: hex_md5(hex_md5(this.form.password) + str),
                  newPassword: hex_md5(hex_md5(this.form.newPassword) + str),
                  surePassword: hex_md5(hex_md5(this.form.confirmPassword) + str)
                },
                'post'
              )
              .then(res => {
                this.$message.success('修改成功，请重新登录！');
                this.dialogVisible = false;
                this.$refs['form'].resetFields();
                setTimeout(() => {
                  this.logout();
                }, 1000);
              });
          }
        }
      });
    },
    collapse() {
      this.$store.commit('collapse');
    },
    modifyPwd() {
      this.dialogVisible = true;
    },
    logout() {
      this.$router.push({ path: '/login' });
      localStorage.clear();
    },
    //tab标签点击时，切换相应的路由
    tabClick(tab) {
      console.log("tab", tab);
      console.log('active', this.activeIndex);
      this.$router.push({ path: this.activeIndex });
    },
    //移除tab标签
    tabRemove(targetName) {
      console.log("tabRemove", targetName);
      //首页不删

      if (targetName == '/main/index') {
        return
      }
      this.$store.commit('delete_tabs', targetName);
      if (this.activeIndex === targetName) {
        // 设置当前激活的路由
        if (this.openTab && this.openTab.length >= 1) {
          console.log('=============', this.openTab[this.openTab.length - 1].route)
          this.$store.commit('set_active_index', this.openTab[this.openTab.length - 1].route);
          this.$router.push({ path: this.activeIndex });
        } else {
          this.$router.push({ path: '/' });
        }
      }
    }
  }
}

</script>
<style lang="scss" scoped>
.view {
  margin: 20px;
  // background: #fff;
}

.dialog-footer {
  text-align: center !important;
}

.el-dropdown {
  cursor: pointer;
  padding-right: 10px;
}

.el-input {
  width: 80%;
}

.content {
  width: calc(100% - 200px);
  float: right;
  // background: #f6f6f6;
  padding: 0 20px;
  border-box: box-sizing;

  .setting {
    position: absolute;
    top: 50%;
    right: 8px;
    transform: translateY(-50%);
    font-size: 0.45rem;
    z-index: 1000;

    .systemTime {
      margin-right: 20px;
      color: rgba(0, 0, 0, 0.65);
    }
  }

  .top {
    position: fixed;
    height: 66px;
    font-size: 50px;
    border-bottom: 1px solid #e9e9e9;
    box-sizing: border-box;
    width: calc(100% - 200px);
    z-index: 100;

    &.root {
      height: 66px;
      line-height: 66px;
      font-size: 14px;
      padding-left: 55px;
      color: #737373;
      background: #fff;

      .paths {
        color: #262626;
      }
    }

    .collapes {
      position: absolute;
      top: 50%;
      left: 10px;
      transform: translateY(-50%);
      z-index: 1000;

      i {
        display: block;
        width: 20px;
        height: 15px;
      }

      .collapse-hide {
        background: url(../../assets/collapse-hide.png);
      }

      .collapse-show {
        background: url(../../assets/collapse-show.png);
      }
    }
  }
}

.username {
  max-width: 130px;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: text-bottom;
  padding: 2px 0;
  cursor: pointer;
}

.content {
  position: relative;
  top: 66px;
}

</style>
